package com.oschina.basic.multi;

import java.util.Random;
import java.util.concurrent.CountDownLatch;

public class MCountDownLatch {

	public static void main(String[] args) {

		try {
			long timeTasks = timeTasks(10, new Runnable() {

				@Override
				public void run() {
					Random r = new Random(System.nanoTime());
					int time = r.nextInt(1000);
					try {
						System.out.println(Thread.currentThread().getName()
								+ " sleeping " + time);
						Thread.sleep(time);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}

				}
			});

			System.out.println("total " + timeTasks);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	public static long timeTasks(int nThreads, final Runnable task)
			throws InterruptedException {

		final CountDownLatch start = new CountDownLatch(1);
		final CountDownLatch end = new CountDownLatch(nThreads);

		for (int i = 0; i < nThreads; i++) {
			new Thread() {
				@Override
				public void run() {
					try {
						start.await();
						task.run();
					} catch (Exception e) {
					} finally {
						end.countDown();
					}
				}
			}.start();
		}

		long startT = System.currentTimeMillis();
		start.countDown();
		end.await();
		long endT = System.currentTimeMillis();
		return endT - startT;

	}

}

